<template>
  <div class="product-detail-page">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-section py-2">
      <div class="container">
        <nav aria-label="breadcrumb">
          <ol class="breadcrumb mb-0">
            <li class="breadcrumb-item">
              <router-link to="/">首页</router-link>
            </li>
            <li class="breadcrumb-item">
              <router-link to="/products">商品列表</router-link>
            </li>
            <li class="breadcrumb-item" v-if="product.categoryName">{{ product.categoryName }}</li>
            <li class="breadcrumb-item active" aria-current="page">{{ product.name || '商品详情' }}</li>
          </ol>
        </nav>
      </div>
    </div>

    <div class="container py-4" v-if="!loading && product.id">
      <div class="row">
        <!-- 左侧：商品图片 -->
        <div class="col-lg-5">
          <div class="product-gallery">
            <!-- 主图显示 -->
            <div class="main-image mb-3">
              <div class="image-container position-relative">
                <img
                  :src="currentImage"
                  :alt="product.name"
                  class="img-fluid rounded"
                  @click="() => openImageModal()"
                >
                <div class="image-badges">
                  <span v-if="product.isNew" class="badge bg-success">新品</span>
                  <span v-if="product.isHot" class="badge bg-danger">热卖</span>
                  <span v-if="product.discount > 0" class="badge bg-warning">{{ product.discount }}折</span>
                </div>
                <button class="btn btn-light image-zoom-btn" @click="() => openImageModal()">
                  <i class="fas fa-search-plus"></i>
                </button>
              </div>
            </div>

            <!-- 缩略图 -->
            <div class="thumbnail-images">
              <div class="d-flex flex-wrap gap-2">
                <div
                  v-for="(image, index) in product.images"
                  :key="index"
                  class="thumbnail-item"
                  :class="{ active: currentImage === image }"
                  @click="currentImage = image"
                >
                  <img :src="image" :alt="`${product.name} 图片 ${index + 1}`" class="img-fluid rounded">
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：商品信息 -->
        <div class="col-lg-7">
          <div class="product-info">
            <!-- 商品标题 -->
            <h1 class="product-title mb-3">{{ product.name }}</h1>

            <!-- 商品副标题 -->
            <p class="product-subtitle text-muted mb-4">{{ product.subtitle }}</p>

            <!-- 评价信息 -->
            <div class="product-rating d-flex align-items-center mb-4">
              <div class="stars me-2">
                <i
                  v-for="n in 5"
                  :key="n"
                  class="fas fa-star"
                  :class="n <= product.rating ? 'text-warning' : 'text-light'"
                ></i>
              </div>
              <span class="rating-score me-3">{{ product.rating }}/5</span>
              <a href="#reviews" class="text-decoration-none">{{ product.reviewCount }} 条评价</a>
              <span class="mx-2">|</span>
              <span class="text-muted">已售 {{ product.salesCount }} 件</span>
            </div>

            <!-- 价格信息 -->
            <div class="product-price mb-4">
              <div class="price-row d-flex align-items-baseline mb-2">
                <span class="current-price text-danger fw-bold me-3">¥{{ selectedPrice }}</span>
                <span v-if="product.originalPrice > product.price"
                      class="original-price text-muted text-decoration-line-through">
                  ¥{{ product.originalPrice }}
                </span>
                <span v-if="product.discount > 0" class="discount-badge badge bg-danger ms-2">
                  省¥{{ (product.originalPrice - product.price).toFixed(0) }}
                </span>
              </div>
              <div class="price-info text-muted small">
                <span class="me-3">含税价，免运费</span>
                <span>支持7天无理由退货</span>
              </div>
            </div>

            <!-- 促销信息 -->
            <div class="promotions mb-4" v-if="product.promotions && product.promotions.length > 0">
              <h6 class="mb-2">优惠信息</h6>
              <div class="promotion-list">
                <div
                  class="promotion-item d-flex align-items-center mb-2"
                  v-for="promo in product.promotions"
                  :key="promo.id"
                >
                  <span class="promotion-type badge bg-danger me-2">{{ promo.type }}</span>
                  <span class="promotion-desc">{{ promo.description }}</span>
                </div>
              </div>
            </div>

            <!-- 规格选择 -->
            <div class="product-specs mb-4">
              <!-- 颜色选择 -->
              <div class="spec-group mb-3" v-if="product.colors && product.colors.length > 0">
                <h6 class="spec-title">颜色分类</h6>
                <div class="spec-options d-flex flex-wrap gap-2">
                  <button
                    v-for="color in product.colors"
                    :key="color.name"
                    class="btn btn-outline-secondary spec-option"
                    :class="{ active: selectedColor === color.name }"
                    @click="selectColor(color)"
                  >
                    {{ color.name }}
                  </button>
                </div>
              </div>

              <!-- 尺寸选择 -->
              <div class="spec-group mb-3" v-if="product.sizes && product.sizes.length > 0">
                <h6 class="spec-title">尺寸规格</h6>
                <div class="spec-options d-flex flex-wrap gap-2">
                  <button
                    v-for="size in product.sizes"
                    :key="size.name"
                    class="btn btn-outline-secondary spec-option"
                    :class="{ active: selectedSize === size.name, disabled: !size.inStock }"
                    :disabled="!size.inStock"
                    @click="selectSize(size)"
                  >
                    {{ size.name }}
                    <span v-if="!size.inStock" class="ms-1 text-muted">(缺货)</span>
                  </button>
                </div>
              </div>

              <!-- 版本选择 -->
              <div class="spec-group mb-3" v-if="product.versions && product.versions.length > 0">
                <h6 class="spec-title">版本规格</h6>
                <div class="spec-options d-flex flex-wrap gap-2">
                  <button
                    v-for="version in product.versions"
                    :key="version.name"
                    class="btn btn-outline-secondary spec-option"
                    :class="{ active: selectedVersion === version.name }"
                    @click="selectVersion(version)"
                  >
                    {{ version.name }}
                    <span class="text-primary ms-1">+¥{{ version.priceAdd || 0 }}</span>
                  </button>
                </div>
              </div>
            </div>

            <!-- 数量选择 -->
            <div class="quantity-section mb-4">
              <h6 class="mb-2">购买数量</h6>
              <div class="d-flex align-items-center">
                <div class="quantity-input d-flex align-items-center me-3">
                  <button class="btn btn-outline-secondary btn-sm" @click="decreaseQuantity" :disabled="quantity <= 1">
                    <i class="fas fa-minus"></i>
                  </button>
                  <input
                    type="number"
                    class="form-control text-center mx-2"
                    style="width: 80px;"
                    v-model="quantity"
                    :min="1"
                    :max="product.stock"
                  >
                  <button class="btn btn-outline-secondary btn-sm" @click="increaseQuantity"
                          :disabled="quantity >= product.stock">
                    <i class="fas fa-plus"></i>
                  </button>
                </div>
                <span class="text-muted">库存 {{ product.stock }} 件</span>
              </div>
            </div>

            <!-- 购买按钮 -->
            <div class="purchase-buttons mb-4">
              <div class="d-flex gap-3 flex-wrap">
                <button
                  class="btn btn-danger btn-lg flex-fill"
                  @click="buyNow"
                  :disabled="!canPurchase || !product.id"
                >
                  <i class="fas fa-bolt me-2"></i>
                  {{ !product.id ? '商品不存在' : '立即购买' }}
                </button>
                <button
                  class="btn btn-warning btn-lg flex-fill"
                  @click="addToCart"
                  :disabled="!canPurchase || !product.id"
                >
                  <i class="fas fa-shopping-cart me-2"></i>
                  {{ !product.id ? '商品不存在' : '加入购物车' }}
                </button>

              </div>
            </div>

            <!-- 商品服务 -->
            <div class="product-services">
              <h6 class="mb-3">服务保障</h6>
              <div class="services-grid">
                <div class="service-item d-flex align-items-center mb-2">
                  <i class="fas fa-shipping-fast text-primary me-2"></i>
                  <span>快速配送：24小时内发货</span>
                </div>
                <div class="service-item d-flex align-items-center mb-2">
                  <i class="fas fa-shield-alt text-success me-2"></i>
                  <span>正品保证：假一赔十</span>
                </div>
                <div class="service-item d-flex align-items-center mb-2">
                  <i class="fas fa-undo text-info me-2"></i>
                  <span>退换服务：7天无理由退货</span>
                </div>
                <div class="service-item d-flex align-items-center mb-2">
                  <i class="fas fa-headset text-warning me-2"></i>
                  <span>售后服务：24小时在线客服</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 商品详情标签页 -->
      <div class="product-details-tabs mt-5">
        <nav class="nav nav-tabs" id="product-tabs" role="tablist">
          <button
            class="nav-link active"
            id="details-tab"
            data-bs-toggle="tab"
            data-bs-target="#details"
            type="button"
            role="tab"
          >
            商品详情
          </button>
          <button
            class="nav-link"
            id="specs-tab"
            data-bs-toggle="tab"
            data-bs-target="#specs"
            type="button"
            role="tab"
          >
            规格参数
          </button>
          <button
            class="nav-link"
            id="reviews-tab"
            data-bs-toggle="tab"
            data-bs-target="#reviews"
            type="button"
            role="tab"
          >
            用户评价 ({{ product.reviewCount }})
          </button>
          <button
            class="nav-link"
            id="qa-tab"
            data-bs-toggle="tab"
            data-bs-target="#qa"
            type="button"
            role="tab"
          >
            问答
          </button>
        </nav>

        <div class="tab-content mt-4" id="product-tab-content">
          <!-- 商品详情 -->
          <div class="tab-pane fade show active" id="details" role="tabpanel">
            <div class="product-description">
              <div v-html="product.description"></div>

              <!-- 商品详情图片 -->
              <div class="detail-images mt-4" v-if="product.detailImages">
                <img
                  v-for="(image, index) in product.detailImages"
                  :key="index"
                  :src="image"
                  :alt="`商品详情图 ${index + 1}`"
                  class="img-fluid mb-3 rounded"
                >
              </div>
            </div>
          </div>

          <!-- 规格参数 -->
          <div class="tab-pane fade" id="specs" role="tabpanel">
            <div class="specs-table">
              <table class="table table-borderless">
                <tbody>
                <tr v-for="spec in product.specifications" :key="spec.name">
                  <td class="spec-name fw-bold text-muted" style="width: 200px;">{{ spec.name }}</td>
                  <td class="spec-value">{{ spec.value }}</td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>

          <!-- 用户评价 -->
          <div class="tab-pane fade" id="reviews" role="tabpanel">
            <div class="reviews-section">
              <!-- 评价统计 -->
              <div class="review-stats mb-4 p-4 bg-light rounded">
                <div class="row text-center">
                  <div class="col-md-3">
                    <div class="stat-item">
                      <div class="stat-number h3 text-warning">{{ product.rating }}</div>
                      <div class="stat-label text-muted">综合评分</div>
                    </div>
                  </div>
                  <div class="col-md-3">
                    <div class="stat-item">
                      <div class="stat-number h3 text-primary">{{ product.reviewCount }}</div>
                      <div class="stat-label text-muted">评价总数</div>
                    </div>
                  </div>
                  <div class="col-md-3">
                    <div class="stat-item">
                      <div class="stat-number h3 text-success">
                        {{ ((product.positiveReviews / product.reviewCount) * 100).toFixed(1) }}%
                      </div>
                      <div class="stat-label text-muted">好评率</div>
                    </div>
                  </div>
                  <div class="col-md-3">
                    <div class="stat-item">
                      <div class="stat-number h3 text-info">{{ product.imageReviews || 0 }}</div>
                      <div class="stat-label text-muted">晒图评价</div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 评价筛选 -->
              <div class="review-filters mb-4">
                <div class="btn-group" role="group">
                  <input type="radio" class="btn-check" id="all-reviews" v-model="reviewFilter" value="all">
                  <label class="btn btn-outline-primary" for="all-reviews">全部</label>

                  <input type="radio" class="btn-check" id="good-reviews" v-model="reviewFilter" value="good">
                  <label class="btn btn-outline-primary" for="good-reviews">好评</label>

                  <input type="radio" class="btn-check" id="medium-reviews" v-model="reviewFilter" value="medium">
                  <label class="btn btn-outline-primary" for="medium-reviews">中评</label>

                  <input type="radio" class="btn-check" id="bad-reviews" v-model="reviewFilter" value="bad">
                  <label class="btn btn-outline-primary" for="bad-reviews">差评</label>

                  <input type="radio" class="btn-check" id="image-reviews" v-model="reviewFilter" value="image">
                  <label class="btn btn-outline-primary" for="image-reviews">有图</label>
                </div>
              </div>

              <!-- 评价列表 -->
              <div class="reviews-list">
                <div class="review-item p-4 border rounded mb-3" v-for="review in filteredReviews" :key="review.id">
                  <div class="review-header d-flex justify-content-between mb-3">
                    <div class="reviewer-info d-flex align-items-center">
                      <img :src="review.avatar" :alt="review.username" class="reviewer-avatar rounded-circle me-3">
                      <div>
                        <div class="reviewer-name fw-bold">{{ review.username }}</div>
                        <div class="review-date text-muted small">{{ formatDate(review.date) }}</div>
                      </div>
                    </div>
                    <div class="review-rating">
                      <div class="stars">
                        <i
                          v-for="n in 5"
                          :key="n"
                          class="fas fa-star"
                          :class="n <= review.rating ? 'text-warning' : 'text-light'"
                        ></i>
                      </div>
                    </div>
                  </div>

                  <div class="review-specs text-muted small mb-2" v-if="review.specs">
                    已购买：{{ review.specs.join('，') }}
                  </div>

                  <div class="review-content mb-3">
                    {{ review.content }}
                  </div>

                  <div class="review-images mb-3" v-if="review.images && review.images.length > 0">
                    <div class="d-flex flex-wrap gap-2">
                      <img
                        v-for="image in review.images"
                        :key="image"
                        :src="image"
                        class="review-image rounded"
                        @click="() => openImageModal(image)"
                      >
                    </div>
                  </div>

                  <div class="review-actions d-flex align-items-center text-muted small">
                    <button class="btn btn-link btn-sm p-0 me-3">
                      <i class="fas fa-thumbs-up me-1"></i>
                      有用 ({{ review.helpful }})
                    </button>
                    <button class="btn btn-link btn-sm p-0">
                      <i class="fas fa-reply me-1"></i>
                      回复
                    </button>
                  </div>
                </div>
              </div>

              <!-- 加载更多评价 -->
              <div class="text-center mt-4" v-if="hasMoreReviews">
                <button class="btn btn-outline-primary" @click="loadMoreReviews">
                  加载更多评价
                </button>
              </div>
            </div>
          </div>

          <!-- 问答 -->
          <div class="tab-pane fade" id="qa" role="tabpanel">
            <div class="qa-section">
              <div class="qa-item p-3 border rounded mb-3" v-for="qa in product.qas" :key="qa.id">
                <div class="question mb-2">
                  <i class="fas fa-question-circle text-primary me-2"></i>
                  <strong>Q: {{ qa.question }}</strong>
                </div>
                <div class="answer text-muted ms-4">
                  <i class="fas fa-comment-alt text-success me-2"></i>
                  A: {{ qa.answer }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载中 -->
    <div v-if="loading" class="text-center py-5">
      <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">加载中...</span>
      </div>
      <div class="mt-2">加载中...</div>
    </div>

    <!-- 商品未找到 -->
    <div v-if="!loading && !product.id" class="text-center py-5">
      <i class="fas fa-exclamation-triangle fa-4x text-muted mb-3"></i>
      <h4>商品未找到</h4>
      <p class="text-muted">抱歉，您访问的商品不存在或已下架</p>
      <router-link to="/products" class="btn btn-primary">
        返回商品列表
      </router-link>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { Message } from '@/utils/message'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 占位符图片生成函数
const placeholderImage = (width: number, height: number) => {
  return `https://picsum.photos/${width}/${height}?random=${Math.floor(Math.random() * 1000)}`
}

// 页面状态
const loading = ref(false)
const currentImage = ref('')

// 选择的规格
const selectedColor = ref('')
const selectedSize = ref('')
const selectedVersion = ref('')
const quantity = ref(1)

// 评价筛选
const reviewFilter = ref('all')

// 商品数据
const product = ref<any>({
  id: 0,
  name: '',
  subtitle: '',
  price: 0,
  originalPrice: 0,
  discount: 0,
  rating: 0,
  reviewCount: 0,
  salesCount: 0,
  stock: 0,
  categoryName: '',
  description: '',
  images: [],
  detailImages: [],
  colors: [],
  sizes: [],
  versions: [],
  specifications: [],
  promotions: [],
  reviews: [],
  qas: [],
  isNew: false,
  isHot: false,
  positiveReviews: 0,
  imageReviews: 0
})

// 推荐商品
const recommendedProducts = ref<any[]>([])

// 计算属性
const selectedPrice = computed(() => {
  let price = product.value.price
  if (selectedVersion.value) {
    const version = product.value.versions.find((v: { name: string }) => v.name === selectedVersion.value)
    if (version && version.priceAdd) {
      price += version.priceAdd
    }
  }
  return price
})

const canPurchase = computed(() => {
  return product.value && product.value.id && product.value.id > 0 && 
         product.value.stock > 0 && quantity.value > 0 && quantity.value <= product.value.stock
})

const filteredReviews = computed(() => {
  if (!product.value.reviews) return []

  switch (reviewFilter.value) {
    case 'good':
      return product.value.reviews.filter((r: { rating: number }) => r.rating >= 4)
    case 'medium':
      return product.value.reviews.filter((r: { rating: number }) => r.rating === 3)
    case 'bad':
      return product.value.reviews.filter((r: { rating: number }) => r.rating <= 2)
    case 'image':
      return product.value.reviews.filter((r: { images: string | any[] }) => r.images && r.images.length > 0)
    default:
      return product.value.reviews
  }
})

const hasMoreReviews = ref(true)

// 模拟商品数据
const mockProduct = {
  id: 1,
  name: 'Apple iPhone 14 Pro 128GB 深空黑色 5G手机',
  subtitle: '6.1英寸超视网膜XDR显示屏 A16仿生芯片 4800万像素专业级摄像头系统',
  price: 7999,
  originalPrice: 8999,
  discount: 8.9,
  rating: 4.8,
  reviewCount: 1234,
  salesCount: 5678,
  stock: 99,
  categoryName: '手机通讯',
  description: '<p>全新iPhone 14 Pro，搭载A16仿生芯片，配备专业级摄像头系统，带来前所未有的拍摄体验...</p>',
  images: [
    placeholderImage(500, 500),
    placeholderImage(500, 500),
    placeholderImage(500, 500),
    placeholderImage(500, 500)
  ],
  detailImages: [
    placeholderImage(800, 600),
    placeholderImage(800, 600),
    placeholderImage(800, 600)
  ],
  colors: [
    { name: '深空黑色', code: '#000000', inStock: true },
    { name: '银色', code: '#C0C0C0', inStock: true },
    { name: '金色', code: '#FFD700', inStock: false },
    { name: '暗紫色', code: '#663399', inStock: true }
  ],
  sizes: [
    { name: '128GB', inStock: true },
    { name: '256GB', inStock: true },
    { name: '512GB', inStock: true },
    { name: '1TB', inStock: false }
  ],
  versions: [
    { name: '标准版', priceAdd: 0 },
    { name: '套装版', priceAdd: 200 }
  ],
  specifications: [
    { name: '品牌', value: 'Apple' },
    { name: '型号', value: 'iPhone 14 Pro' },
    { name: '颜色', value: '深空黑色' },
    { name: '存储容量', value: '128GB' },
    { name: '屏幕尺寸', value: '6.1英寸' },
    { name: '操作系统', value: 'iOS 16' },
    { name: '处理器', value: 'A16 仿生芯片' },
    { name: '摄像头', value: '4800万像素主摄 + 1200万像素超广角 + 1200万像素长焦' }
  ],
  promotions: [
    { id: 1, type: '满减', description: '满5000减200，满8000减500' },
    { id: 2, type: '分期', description: '支持12期免息分期付款' },
    { id: 3, type: '赠品', description: '购买即送原装保护壳+钢化膜' }
  ],
  reviews: [
    {
      id: 1,
      username: '张***3',
      avatar: placeholderImage(50, 50),
      rating: 5,
      date: new Date('2024-01-15'),
      content: '手机收到了，包装很好，外观漂亮，系统流畅，摄像头效果很棒，总体非常满意！',
      specs: ['深空黑色', '128GB'],
      images: [placeholderImage(100, 100), placeholderImage(100, 100)],
      helpful: 15
    },
    {
      id: 2,
      username: '李***8',
      avatar: placeholderImage(50, 50),
      rating: 4,
      date: new Date('2024-01-10'),
      content: '用了几天了，整体体验不错，就是价格有点贵，不过品质确实好。',
      specs: ['银色', '256GB'],
      images: [],
      helpful: 8
    }
  ],
  qas: [
    {
      id: 1,
      question: '这款手机支持5G网络吗？',
      answer: '是的，iPhone 14 Pro支持5G网络，包括Sub-6GHz和毫米波频段。'
    },
    {
      id: 2,
      question: '电池续航能力怎么样？',
      answer: 'iPhone 14 Pro的电池续航比上一代提升约1小时，正常使用可以支撑一整天。'
    }
  ],
  isNew: true,
  isHot: true,
  positiveReviews: 1100,
  imageReviews: 234
}

// 推荐商品数据
const mockRecommendedProducts = [
  {
    id: 2,
    name: '华为 Mate 50 Pro',
    price: 5999,
    thumbnail: placeholderImage(200, 200)
  },
  {
    id: 3,
    name: '小米 13 Pro',
    price: 4299,
    thumbnail: placeholderImage(200, 200)
  },
  {
    id: 4,
    name: 'iPhone 保护壳',
    price: 199,
    thumbnail: placeholderImage(200, 200)
  },
  {
    id: 5,
    name: '苹果原装充电器',
    price: 299,
    thumbnail: placeholderImage(200, 200)
  },
  {
    id: 6,
    name: 'AirPods Pro',
    price: 1899,
    thumbnail: placeholderImage(200, 200)
  },
  {
    id: 7,
    name: '钢化膜',
    price: 39,
    thumbnail: placeholderImage(200, 200)
  }
]

// 方法
const fetchProduct = async () => {
  const productId = route.params.id
  if (!productId) {
    Message.error('商品ID不存在')
    router.push('/products')
    return
  }

  loading.value = true
  try {
    // 调用真实API获取商品详情
    const { getProductDetail } = await import('@/api/product')
    const response = await getProductDetail(Number(productId))
    const apiProduct = response.data

    if (!apiProduct || apiProduct.status !== 1) {
      // 商品不存在或已下架
      product.value = { id: 0 }
      return
    }

    // 将API数据映射到页面数据结构
    product.value = {
      id: apiProduct.id,
      name: apiProduct.name,
      subtitle: apiProduct.description || '',
      price: apiProduct.price,
      originalPrice: apiProduct.marketPrice || apiProduct.price,
      discount: apiProduct.marketPrice ? Number(((apiProduct.marketPrice - apiProduct.price) / apiProduct.marketPrice * 100).toFixed(1)) : 0,
      rating: 4.8, // 暂时使用默认评分
      reviewCount: 1234, // 暂时使用默认值
      salesCount: apiProduct.salesCount || 0,
      stock: apiProduct.stock,
      categoryName: '商品分类', // 暂时使用默认值
      description: apiProduct.description || '',
      images: [
        placeholderImage(500, 500),
        placeholderImage(500, 500),
        placeholderImage(500, 500),
        placeholderImage(500, 500)
      ],
      detailImages: [
        placeholderImage(800, 600),
        placeholderImage(800, 600),
        placeholderImage(800, 600)
      ],
      colors: [
        { name: '默认', code: '#000000', inStock: true }
      ],
      sizes: [
        { name: '标准', inStock: true }
      ],
      versions: [
        { name: '标准版', priceAdd: 0 }
      ],
      specifications: [
        { name: '品牌', value: apiProduct.brandId ? `品牌ID: ${apiProduct.brandId}` : '未知' },
        { name: '商品名称', value: apiProduct.name },
        { name: '价格', value: `¥${apiProduct.price}` },
        { name: '库存', value: `${apiProduct.stock}件` }
      ],
      promotions: [
        { id: 1, type: '正品', description: '100%正品保证' },
        { id: 2, type: '售后', description: '7天无理由退货' }
      ],
      reviews: mockProduct.reviews, // 暂时使用模拟评价数据
      qas: mockProduct.qas, // 暂时使用模拟问答数据
      isNew: false,
      isHot: apiProduct.isHot === 1,
      positiveReviews: 1100,
      imageReviews: 234
    }

    // 设置主图
    currentImage.value = product.value.images[0] || placeholderImage(500, 500)
    recommendedProducts.value = mockRecommendedProducts

    // 设置默认选项
    if (product.value.colors.length > 0) {
      selectedColor.value = product.value.colors[0].name
    }
    if (product.value.sizes.length > 0) {
      selectedSize.value = product.value.sizes[0].name
    }
    if (product.value.versions.length > 0) {
      selectedVersion.value = product.value.versions[0].name
    }

  } catch (error: any) {
    console.error('获取商品详情失败:', error)
    if (error.response?.status === 404) {
      // 商品不存在
      product.value = { id: 0 }
      Message.error('商品不存在或已下架')
    } else {
      Message.error('获取商品详情失败：' + (error.message || '网络错误'))
    }
  } finally {
    loading.value = false
  }
}

const selectColor = (color: any) => {
  if (color.inStock) {
    selectedColor.value = color.name
  }
}

const selectSize = (size: any) => {
  if (size.inStock) {
    selectedSize.value = size.name
  }
}

const selectVersion = (version: any) => {
  selectedVersion.value = version.name
}

const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

const increaseQuantity = () => {
  if (quantity.value < product.value.stock) {
    quantity.value++
  }
}

const addToCart = async () => {
  if (!userStore.isLoggedIn) {
    Message.warning('请先登录')
    router.push('/login')
    return
  }

  if (!product.value || !product.value.id || product.value.id === 0) {
    Message.error('商品信息无效，请刷新页面重试')
    return
  }

  if (!canPurchase.value) {
    Message.warning('商品库存不足')
    return
  }

  try {
    await cartStore.addToCart(product.value.id, quantity.value)
    Message.success('已添加到购物车')
  } catch (error: any) {
    console.error('添加到购物车失败:', error)
    const errorMessage = error.message || '添加失败，请重试'
    Message.error(errorMessage)
  }
}

const buyNow = async () => {
  if (!userStore.isLoggedIn) {
    Message.warning('请先登录')
    router.push('/login')
    return
  }

  if (!product.value || !product.value.id || product.value.id === 0) {
    Message.error('商品信息无效，请刷新页面重试')
    return
  }

  if (!canPurchase.value) {
    Message.warning('商品库存不足')
    return
  }

  // 直接跳转到结算页面
  router.push({
    path: '/checkout',
    query: {
      productId: product.value.id,
      quantity: quantity.value,
      color: selectedColor.value,
      size: selectedSize.value,
      version: selectedVersion.value
    }
  })
}



const openImageModal = (image?: string) => {
  // 这里可以实现图片放大查看功能
  // 可以使用模态框或者图片查看器组件
  console.log('打开图片:', image || currentImage.value)
}

const loadMoreReviews = () => {
  // 模拟加载更多评价
  // 实际实现中这里应该调用API加载更多数据
  hasMoreReviews.value = false
  Message.success('没有更多评价了')
}

const formatDate = (date: Date) => {
  return date.toLocaleDateString('zh-CN')
}

// 监听路由变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    fetchProduct()
  }
}, { immediate: true })

onMounted(() => {
  fetchProduct()
})
</script>

<style scoped>
.breadcrumb-section {
  background: white !important;
  border-bottom: 1px solid #f0f0f0;
}

.breadcrumb {
  margin-bottom: 0;
  font-size: 12px;
  padding: 0;
  background: transparent;
}

.breadcrumb-item {
  color: #999;
  font-size: 12px;
}

.breadcrumb-item a {
  color: #999;
  text-decoration: none;
  padding: 1px 3px;
  border-radius: 2px;
  transition: all 0.2s ease;
}

.breadcrumb-item a:hover {
  color: #007bff;
  background: rgba(0, 123, 255, 0.05);
}

.breadcrumb-item.active {
  color: #666;
  font-weight: 400;
}

.breadcrumb-item + .breadcrumb-item::before {
  content: "/";
  color: #ddd;
  margin: 0 5px;
  font-weight: 300;
  font-size: 11px;
}

/* 商品图片画廊 */
.product-gallery .main-image {
  position: relative;
}

.image-container {
  border-radius: 10px;
  overflow: hidden;
}

.image-container img {
  width: 100%;
  height: 400px;
  object-fit: cover;
  cursor: zoom-in;
}

.image-badges {
  position: absolute;
  top: 15px;
  left: 15px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.image-zoom-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.thumbnail-item {
  width: 80px;
  height: 80px;
  border: 2px solid transparent;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.thumbnail-item:hover,
.thumbnail-item.active {
  border-color: #007bff;
}

.thumbnail-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 商品信息 */
.product-title {
  font-size: 1.5rem;
  font-weight: 600;
  line-height: 1.4;
}

.product-subtitle {
  font-size: 1rem;
  line-height: 1.5;
}

.product-rating .stars {
  font-size: 14px;
}

.product-rating a {
  color: #007bff;
  text-decoration: none;
}

.product-price .current-price {
  font-size: 2rem;
}

.product-price .original-price {
  font-size: 1.2rem;
}

/* 促销信息 */
.promotion-item {
  background: #f8f9fa;
  border-radius: 5px;
  padding: 8px 12px;
}

.promotion-type {
  min-width: 40px;
  font-size: 10px;
}

/* 规格选择 */
.spec-title {
  font-size: 1rem;
  font-weight: 600;
  margin-bottom: 10px;
}

.spec-option {
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.spec-option.active {
  background-color: #007bff;
  border-color: #007bff;
  color: white;
}

.spec-option:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 数量选择 */
.quantity-input button {
  width: 32px;
  height: 32px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity-input input {
  border: 1px solid #dee2e6;
  border-left: none;
  border-right: none;
}

/* 购买按钮 */
.purchase-buttons .btn {
  min-height: 48px;
  font-weight: 500;
}

/* 服务保障 */
.services-grid {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
}

.service-item {
  font-size: 14px;
}

/* 详情标签页 */
.nav-tabs .nav-link {
  font-weight: 500;
  color: #666;
  border: none;
  border-bottom: 3px solid transparent;
  background: none;
}

.nav-tabs .nav-link.active {
  color: #007bff;
  border-bottom-color: #007bff;
  background: none;
}

/* 规格参数表格 */
.specs-table .table td {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.spec-name {
  background: #f8f9fa;
  padding-left: 15px;
}

/* 评价部分 */
.review-stats .stat-item {
  padding: 10px;
}

.review-stats .stat-number {
  margin-bottom: 5px;
}

.review-filters .btn-check:checked + .btn {
  background-color: #007bff;
  color: white;
}

.review-item {
  background: #fafafa;
}

.reviewer-avatar {
  width: 50px;
  height: 50px;
}

.reviewer-name {
  font-size: 14px;
}

.review-date {
  font-size: 12px;
}

.review-rating .stars {
  font-size: 12px;
}

.review-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  cursor: pointer;
}

.review-actions .btn-link {
  color: #666;
  text-decoration: none;
  font-size: 12px;
}

/* 推荐商品 */
.recommended-products .product-card {
  border: none;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.recommended-products .product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}

.recommended-products .card-img-top {
  height: 150px;
  object-fit: cover;
}

.recommended-products .product-name {
  font-size: 13px;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.recommended-products .product-name a {
  color: #333;
  text-decoration: none;
}

.recommended-products .product-name a:hover {
  color: #007bff;
}
</style> 